﻿using System;
using System.Text;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.IO;
using System.Linq;

namespace FileUtility
{
    public static class ExtString
    {
        public static int GetLength(this string s)
        {
            return s.Length;
        }
        public static string[] Split(this string strLine, int[] unitLengthArr)
        {
            string[] strArr = new string[unitLengthArr.Length];
            int currentPosition = 0;
            int i = 0;
            int length = unitLengthArr.Sum();
            //if (length  strLine.Length)
            //{
            //    throw new Exception("Sum of unitLengthArr not larger length of strLine");

            //}
            unitLengthArr.ToList().ForEach(len =>
            {
                if (currentPosition + len <= strLine.Length)
                {
                    string str = strLine.Substring(currentPosition, len);
                    strArr[i] = str;
                }
                else
                {
                    
                }
                currentPosition = currentPosition + len;
                i++;
            });
            return strArr;
        }
    }

    public class Utility
    {
      
        public static DataTable ReadFileContentToDataTable(string filePath, DataTable dtTarget,Guid batchId,string charSplit)
        {
            string exMsg = "";
            try
            {
               dtTarget.Rows.Clear();
               string[] _strArrContents = System.IO.File.ReadAllLines(filePath, Encoding.GetEncoding("gb2312"));
               if (batchId != null)
               {
                   int count = 0;
                   foreach (string strLine in _strArrContents)
                   {
                       count++;
                       try
                       {
                           string _strLine = batchId.ToString() + charSplit + strLine;
                           string[] _strArrLine = _strLine.Split(charSplit.ToCharArray());
                           DataRow dr = dtTarget.NewRow();
                           dr.ItemArray = _strArrLine;
                           dtTarget.Rows.Add(dr);
                       }
                       catch (Exception ex)
                       {
                           exMsg = exMsg + "Row:" + count + "," + strLine + "," + ex.Message + "\n";
                       }
                   }
               }
               else
               {

                   foreach (string strLine in _strArrContents)
                   {
                       string[] _strArrLine = strLine.Split(charSplit.ToCharArray());
                       DataRow dr = dtTarget.NewRow();
                       if (_strArrLine.Length > dr.ItemArray.Length)
                       {
                           dr.ItemArray = _strArrLine;
                           dtTarget.Rows.Add(dr);
                       }
                   }
               }
              if (!string.IsNullOrEmpty(exMsg))
              {
                  dtTarget.Rows.Clear();
                  throw new Exception(exMsg);
              }
                return dtTarget;
            }
            catch (Exception ex)
            {
                throw new Exception(exMsg);
            }

        }

        public static DataTable ReadFileContentToDataTable(string filePath, DataTable dtTarget, Guid batchId, string charSplit,long startPosition,int rowsCount,out long endPosition)
        {
            dtTarget.Rows.Clear();
            System.IO.FileStream _fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.StreamReader _sr = new System.IO.StreamReader(_fs);
            endPosition = startPosition;
            _fs.Seek(startPosition, SeekOrigin.Current);
            if (batchId != null)
            {
                for (int i = 0; i < rowsCount; i++)
                {
                    string _line = _sr.ReadLine();
                    endPosition = endPosition + _line.Length + 1;
                    DataRow dr = dtTarget.NewRow();
                    _line = batchId.ToString() + charSplit + _line;
                    dr.ItemArray = _line.Split(charSplit.ToCharArray());
                }
            }
            else
            {
                for (int i = 0; i < rowsCount; i++)
                {
                    string _line = _sr.ReadLine();
                    endPosition = endPosition + _line.Length + 1;
                    DataRow dr = dtTarget.NewRow();
                    dr.ItemArray = _line.Split(charSplit.ToCharArray());
                }
            }
            _fs.Close();
            return dtTarget;
            

        }

        public static DataTable ReadFileContentToDataTable(string filePath, DataTable dtTarget, Guid batchId, int[] columnLengthArr)
        {
            string exMsg = "";
            try
            {
                dtTarget.Rows.Clear();
                string[] _strArrContents = System.IO.File.ReadAllLines(filePath, Encoding.GetEncoding("gb2312"));
                if (batchId != null)
                {
                    int count = 0;
                    if (columnLengthArr[0] != 36)
                    {
                        exMsg = "Please set batchId length is 36 at position 0";
                    }
                    
                    foreach (string strLine in _strArrContents)
                    {
                        count++;
                        try
                        {  
                            string _strLine = batchId.ToString() + strLine;
                            string[] _strArrLine = _strLine.Split(columnLengthArr);
                             DataRow dr = dtTarget.NewRow();
                            dr.ItemArray = _strArrLine;
                            dtTarget.Rows.Add(dr);
                        }
                        catch (Exception ex)
                        {
                            exMsg = exMsg + "Row:" + count + "," + strLine + "," + ex.Message + "\n";
                        }
                    }
                   
                }
                else
                {

                    foreach (string strLine in _strArrContents)
                    {
                        string[] _strArrLine = strLine.Split(columnLengthArr);
                        DataRow dr = dtTarget.NewRow();
                        if (_strArrLine.Length > dr.ItemArray.Length)
                        {
                            dr.ItemArray = _strArrLine;
                            dtTarget.Rows.Add(dr);
                        }
                    }
                }
                if (!string.IsNullOrEmpty(exMsg))
                {
                    dtTarget.Rows.Clear();
                    throw new Exception(exMsg);
                }
                return dtTarget;
            }
            catch (Exception ex)
            {
                throw new Exception(exMsg);
            }

        }

        public static Guid GetBatchID(string dataType, SqlDatabase db, string logTable, string prefix,out bool IsNew)
        {
            string sql = "SELECT BatchID FROM " + logTable
                + "(NOLOCK) WHERE Filename='" + prefix
                + "' AND status=-1";
           DataSet ds=db.ExecuteDataSet(CommandType.Text, sql);
           Guid batchId;
           if (ds.Tables[0].Rows.Count > 0)
           {
               batchId = new Guid(ds.Tables[0].Rows[0][0].ToString());
               IsNew = false;
           }
           else
           {
               batchId = Guid.NewGuid();
               IsNew = true;
           }
           return batchId;
        }


        public static DataTable GetDataTableNoData(SqlDatabase db,string targetTableName)
        {
            string sql = "SELECT * FROM " + targetTableName
                + "(NOLOCK) WHERE 1=0";

            DataSet ds = db.ExecuteDataSet(CommandType.Text, sql);
            return ds.Tables[0];
        }

        public static void AddNewFileLog(SqlDatabase db, Guid batchId,string DataType,string DataSource,string fileName,int totalFiles,int FileCount,int RecordCount,int Status,string PlantCode)
        {
            object[] _params = { batchId, DataType, DataSource, fileName, totalFiles, FileCount, RecordCount, Status,"",PlantCode, "CreateNewFile" };
            db.ExecuteNonQuery("Save_TransferLogData_SP", _params);
           // string sqlText = "exec Save_TransferLogData_SP @BatchID={0},@DataType={1},@TransType={2},@DataSource={3},@FileName={4},";
        }

        public static void UpdateImportEndStatus(SqlDatabase db, Guid batchId)
        {
            db.ExecuteNonQuery(CommandType.Text, "exec Save_TransferLogData_SP @TransType='UpdateImportEnd',@BatchId='" + batchId.ToString()+"'");
        }

        public static void AddFileCount(SqlDatabase db, Guid batchId,int recordsCount)
        {
            db.ExecuteNonQuery(CommandType.Text, "exec Save_TransferLogData_SP @TransType='AddFileCounts',@BatchId='" + batchId.ToString() + "',@RecordsCount="+recordsCount.ToString());
        }

        public static string ReadDBNameByPlant(SqlDatabase db, string PlantCode)
        {
            string sql = "SELECT * FROM SAPDBConfigM" 
               + "(NOLOCK) WHERE PlantCode='"+PlantCode+"'";

            DataSet ds = db.ExecuteDataSet(CommandType.Text, sql);
            string dbName="";
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    dbName = ds.Tables[0].Rows[0]["DBConnString"].ToString();
                }
            }
            return dbName;
        }


        public static void SaveException(SqlDatabase db, Guid batchId, string  exceptionMsg,string fileName)
        {
            db.ExecuteNonQuery(CommandType.Text, "exec Save_TransferLogData_SP @TransType='Exception',@BatchId='" + batchId.ToString() + "',@Exception=N'" + exceptionMsg + "',@FileName='" + fileName+"'");
        }

        public static DataTable ReadProcessConfigByPlant(SqlDatabase db, string PlantCode,string DataType)
        {
            string sql = "SELECT * FROM SAPPlantProcessConfigM"
            + "(NOLOCK) WHERE PlantCode='" + PlantCode + "' AND DataType='" + DataType+"'";
            DataSet ds = db.ExecuteDataSet(CommandType.Text, sql);
            return ds.Tables[0];

        }

        public static DataTable ReadAllFileMonitorProcess(SqlDatabase db)
        {
            try
            {
                string sql = "SELECT * FROM FileMonitorProcessM(NOLOCK) WHERE IsActive=1 AND IsLocked=0";
                DataSet ds = db.ExecuteDataSet(CommandType.Text, sql);
                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }


        public static int LockProcess(SqlDatabase db,string ProcessName,string LockedBy)
        {
            try
            {
                string sql=string.Format("UPDATE FileMonitorProcessM SET IsLocked=1,LockedBy='{0}' WHERE ProcessName='{1}'",LockedBy,ProcessName);
                return db.ExecuteNonQuery(CommandType.Text,sql);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }


    }
}
